package com.itheima;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

@WebServlet("/ServletLogin")
public class ServletLogin extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        HashMap<String, String> hm = new HashMap<>();
        String psw = request.getParameter("psw");
        String realPath = getServletContext().getRealPath("/user.txt");
        File file = new File(realPath);
        if (!file.exists()){
            file.createNewFile();
            response.sendRedirect(request.getContextPath()+"/newuser.jsp");
        }else{
            BufferedReader br = new BufferedReader(new FileReader(realPath));
            String s;
            while ((s=br.readLine())!=null){
                String[] split = s.split(":");
                hm.put(split[0],split[1]);
            }
            br.close();
            if (hm.size()!=0&&hm.containsKey(username)&&hm.get(username).equals(psw)){
                request.getSession().setAttribute("username",username);
                response.sendRedirect(request.getContextPath()+"/entry.jsp");
            }else{
                response.getWriter().write("您的账号密码不正确,请重新输入,2s...");
                response.setHeader("Refresh","2;URL=login.jsp");
            }
        }

    }
}
